package need_cutpart

import (
	"fmt"
	"jihe.common/protos/base_server/proto"
	"strings"
)

func (s *Model) Create(req *proto.BaseNeedCutpart) (err error) {
	sqlStr := fmt.Sprintf("INSERT INTO %s (need_id, ratio, img_line, img_face, cutpart_id, after_obj, code, after_dxf_info_url)VALUES($1,$2,$3,$4,$5,$6,$7,$8)", s.Name)
	_, err = s.Db.Exec(sqlStr, req.NeedId, req.Ratio, req.ImgLine, req.ImgFace, req.CutpartId, req.AfterObj, req.Code, req.AfterDxfInfoUrl)
	if err != nil {
		return
	}
	return
}

func (s *Model) DeleteByNeedId(needId string) (err error) {
	sqlStr := fmt.Sprintf("delete from %s where need_id = $1", s.Name)
	_, err = s.Db.Exec(sqlStr, needId)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetListByNeedId(needId string) (ret []*proto.BaseNeedCutpart, err error) {
	sqlStr := fmt.Sprintf("select ratio, img_line, img_face, cutpart_id, after_obj, code, after_dxf_info_url from %s where need_id = $1", s.Name)
	rows, err := s.Db.Query(sqlStr, needId)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		item := &proto.BaseNeedCutpart{}
		err = rows.Scan(&item.Ratio, &item.ImgLine, &item.ImgFace, &item.CutpartId, &item.AfterObj, &item.Code, &item.AfterDxfInfoUrl)
		if err != nil {
			return
		}
		ret = append(ret, item)
	}
	return
}

func (s *Model) Update(req *proto.BaseNeedCutpart) (err error) {
	intoMap := make(map[string]interface{})
	fields, vals := make([]string, 0), make([]interface{}, 0)
	valNum := 0
	for field, val := range intoMap {
		valNum++
		fields = append(fields, fmt.Sprintf("%s=$%d", field, valNum))
		vals = append(vals, val)
	}
	sqlStr := fmt.Sprintf("update %s set "+strings.Join(fields, ",")+" where cutpart_id = '%s'", s.Name, req.CutpartId)
	_, err = s.Db.Exec(sqlStr, vals...)
	if err != nil {
		return
	}
	return
}
